package com.gong.bank.controller;

import com.gong.bank.dao.BankDaoInterface;
import com.gong.bank.model.UserBean;
import com.gong.bank.service.BankService;
import com.gong.bank.service.BankServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author:gong
 * @create: 4/8/2022 上午9:01
 */
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BankService bankService = new BankServiceImpl();
        req.setCharacterEncoding("utf-8");
        String login = req.getParameter("login");
        String register = req.getParameter("register");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserBean user = bankService.findUserByName(username);
        req.setAttribute("user",user);
        if (login!=null){
            if (user !=null  && user.getPassword().equals(password)){
                req.getSession().setAttribute("userInfo",user);
                if (user.getAdmin()==0){
                    req.getRequestDispatcher("main.jsp").forward(req,resp);
                }else if (user.getAdmin()==1){
                    req.getRequestDispatcher("admin.jsp").forward(req,resp);
                }else {
                    req.getRequestDispatcher("error.jsp").forward(req,resp);
                }

            }
        }
        if (register!=null){
            System.out.println(111);
            if (user==null){
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }else {
                System.out.println(222);
                bankService.insertUser(username,password);
                UserBean user1 = bankService.findUserByName(username);
                req.getSession().setAttribute("userInfo",user1);
                req.getRequestDispatcher("main.jsp").forward(req,resp);
            }

        }
    }
}
